package com.study.mybatis.session.defaults;

import com.study.mybatis.common.CommonCons;
import com.study.mybatis.session.Configuration;
import com.study.mybatis.session.SqlSession;
import com.study.mybatis.session.SqlSessionFactory;
import com.study.mybatis.utils.XmlUtil;

import java.io.File;
import java.net.URL;

/**
 * @author yuantongqin
 * 2021/7/31
 **/
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
        // 获取xml配置文件路径
        String location = configuration.getConfig().getProperty(CommonCons.location).replaceAll("\\.", "/");
        // 加载xml配置文件
        loadMappersInfo(location);
    }

    private void loadMappersInfo(String location) {
        if (location == null || "".equals(location)) {
            return;
        }
        URL url = DefaultSqlSessionFactory.class.getClassLoader().getResource(location);
        File file = new File(url.getFile());

        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length <= 0) {
                return;
            }
            for (File f : files) {
                if (f.isDirectory()) {
                    loadMappersInfo(location + File.separator + f.getName());
                } else if (f.getName().endsWith(CommonCons.MAPPER_FILE_SUFFIX)) {
                    // 只对XML文件解析
                    XmlUtil.readMapperXml(f, this.configuration);
                }
            }

        }

    }

    /**
     * 获取一个SqlSession对象
     * @return
     */
    @Override
    public SqlSession openSession() {

        return new DefaultSqlSession(configuration);
    }

    @Override
    public Configuration getConfiguration() {
        return null;
    }
}
